<template>
  <div class="convert-layout">
    <div class="convert-main-layout">
      <!-- 左侧面板 -->
      <div class="left-panel-layout">
        <div class="input-dir-row">
          <el-radio v-model="inputType" label="dir">输入目录(批量):</el-radio>
          <el-input
            v-model="inputDirPath"
            :disabled="inputType !== 'dir'"
          ></el-input>
          <el-button @click="selectInputDir" :disabled="inputType !== 'dir'">
            <el-icon><Folder /></el-icon>
          </el-button>
        </div>

        <el-select v-model="fileType" class="file-type-combo">
          <el-option
            label="视频格式 (*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm *.m4v *.mpg *.mpeg *.vob *.ogv *.mxf *.ts *.m2ts *.divx *.3gp *.asf *.rm *.rmvb)"
            value="video"
          ></el-option>
          <el-option
            label="音频格式 (*.mp3 *.wav *.aac *.flac *.m4a *.wma *.ogg *.ac3 *.aiff *.alac *.ape *.opus *.ra *.wv *.mka *.dts *.mpc)"
            value="audio"
          ></el-option>
          <el-option
            label="图片格式 (*.jpg *.jpeg *.png *.gif *.bmp *.tiff *.webp *.tga *.dpx *.exr *.pam *.pbm *.pcx *.pgm *.ppm *.sgi *.xwd *.heic)"
            value="image"
          ></el-option>
        </el-select>

        <div class="input-file-row">
          <el-radio v-model="inputType" label="file"
            >输入文件(单文件):</el-radio
          >
          <el-input
            v-model="inputFilePath"
            :disabled="inputType !== 'file'"
          ></el-input>
          <el-button @click="selectInputFile" :disabled="inputType !== 'file'">
            <el-icon><Document /></el-icon>
          </el-button>
        </div>

        <div class="output-dir-row">
          <span style="font-size: 14px; white-space: nowrap">输出目录:</span>
          <el-input v-model="outputDirPath"></el-input>
          <el-button @click="selectOutputDir">
            <el-icon><Folder /></el-icon>
          </el-button>
        </div>

        <div class="output-ext-row">
          <el-checkbox v-model="useOutputExt">输出扩展名:</el-checkbox>
          <el-input v-model="outputExt" :disabled="!useOutputExt"></el-input>
        </div>

        <div>
          <span style="font-size: 14px">输出选项:</span>
          <el-input
            type="textarea"
            v-model="outputOptions"
            :rows="4"
          ></el-input>
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel-layout">
        <el-tabs v-model="optionsTab">
          <el-tab-pane label="视频" name="videoTab">
            <div class="options-scrollbar">
              <div class="video-options-list">
                <div
                  v-for="(option, index) in videoOptions"
                  :key="index"
                  class="option-item"
                  @click="selectVideoOption(option)"
                >
                  {{ option }}
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="音频" name="audioTab">
            <div class="options-scrollbar">
              <div class="audio-options-list">
                <div
                  v-for="(option, index) in audioOptions"
                  :key="index"
                  class="option-item"
                  @click="selectAudioOption(option)"
                >
                  {{ option }}
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="图像" name="imageTab">
            <div class="options-scrollbar">
              <div class="image-options-list">
                <div
                  v-for="(option, index) in imageOptions"
                  :key="index"
                  class="option-item"
                  @click="selectImageOption(option)"
                >
                  {{ option }}
                </div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <el-button @click="showOptionsHelp">选项帮助</el-button>
      </div>
    </div>

    <div>
      <span style="font-size: 13px">FFmpeg命令(批量命令仅做展示):</span>
      <el-input type="textarea" v-model="ffmpegCommand" :rows="3"></el-input>
    </div>

    <div>
      <span style="font-size: 13px">FFmpeg日志:</span>
      <FileConverterTable ref="fileConverterTable" />
    </div>

    <el-button
      type="primary"
      @click="runCommand"
      class="run-button"
      :disabled="isRunning"
    >
      {{ isRunning ? "处理中..." : "运行" }}
    </el-button>
  </div>
</template>

<script>
import { ref, reactive, toRefs, onMounted, onUnmounted } from "vue";
import { Folder, Document } from "@element-plus/icons-vue";
import {
  SelectDirectory,
  SelectFile,
  ConvertBatchFiles,
  ConvertSingleFile,
} from "../../../wailsjs/go/main/App";
import { EventsOn, EventsOff } from "../../../wailsjs/runtime/runtime";
import { ElMessage } from "element-plus";
import FileConverterTable from "../FileConverterTable.vue";

export default {
  name: "ConvertTab",
  components: {
    Folder,
    Document,
    FileConverterTable,
  },
  setup() {
    const state = reactive({
      inputType: "dir",
      inputDirPath: "",
      inputFilePath: "",
      fileType: "video",
      outputDirPath: "",
      useOutputExt: false,
      outputExt: "",
      outputOptions: "",
      optionsTab: "videoTab",
      ffmpegCommand: "",
      ffmpegLog: "",
      isRunning: false,

      // 视频选项列表
      videoOptions: [
        "音视频质量不变",
        "WEB视频流优化",
        "H264压缩",
        "H264压缩-intel加速",
        "H264压缩-AMD加速",
        "H264压缩-NV加速",
        "H265压缩",
        "H265压缩-intel加速",
        "H265压缩-AMD加速",
        "H265压缩-NV加速",
        "视频两倍速",
        "视频倒放",
        "设置画面比例",
        "视频0.5倍速 + 光流法补帧到60帧",
        "裁切视频画面",
        "视频旋转度数",
        "水平翻转画面",
        "垂直翻转画面",
        "设定至指定分辨率并且自动填充黑边",
        "转码到mp3",
        "音频两倍速",
        "音频倒放",
        "声音响度标准化",
        "音量大小调节",
        "静音第一个声道",
        "静音所有声道",
        "交换左右声道",
        "gif(15fps,480p)",
        "从视频区间每秒提取n张照片",
        "截取指定数量的帧保存为图片",
        "视频或音乐添加封面图片",
      ],

      // 音频选项列表
      audioOptions: [
        "转码到mp3",
        "音频两倍速",
        "音频倒放",
        "声音响度标准化",
        "音量大小调节",
        "静音第一个声道",
        "静音所有声道",
        "交换左右声道",
      ],

      // 图像选项列表
      imageOptions: [
        "JPEG压缩质量(1-31,越大压缩率越高)",
        "PNG无损压缩(zlib 1-9)",
        "WebP压缩(质量0-100)",
        "从视频区间每秒提取n张照片",
        "截取指定数量的帧保存为图片",
        "视频或音乐添加封面图片",
      ],
    });

    // 添加对FileConverterTable的引用
    const fileConverterTable = ref(null);

    // 节流函数
    const throttle = (func, delay) => {
      let lastCall = 0;
      return (...args) => {
        const now = new Date().getTime();
        if (now - lastCall < delay) {
          return;
        }
        lastCall = now;
        return func(...args);
      };
    };

    // 定义更新进度的函数
    const updateTaskProgress = (taskId, progress) => {
      if (fileConverterTable.value) {
        fileConverterTable.value.updateTaskProgress(taskId, progress);
      }
    };

    // 使用 throttle 包装 updateTaskProgress 函数
    const throttledUpdateTaskProgress = throttle(updateTaskProgress, 1000); // 1秒内只执行一次

    // 用于跟踪已知的任务ID
    const knownTaskIds = new Set();

    // 添加事件监听器
    onMounted(() => {
      EventsOn("ffmpeg_progress", (data) => {
        // 如果是新的任务ID，增加total计数
        if (!knownTaskIds.has(data.taskId)) {
          fileConverterTable.value.updateTaskProgress(data.taskId, data.progress);
          knownTaskIds.add(data.taskId);
        }else{
          throttledUpdateTaskProgress(data.taskId, data.progress);
        }
      });

      EventsOn("ffmpeg_done", (data) => {
        if (fileConverterTable.value) {
          fileConverterTable.value.updateTaskStatus(data.taskId, "done");

          if (state.inputType === "dir") {
            // 处理批量任务
            if (data.allTask == 1) {
              state.isRunning = false;
              // ElMessage.info(data.output);
              ElMessage.success("所有任务已完成");
            }
          } else {
            state.isRunning = false;
            ElMessage.success("任务已完成");
          }
        }
      });
    });

    // 清理事件监听器
    onUnmounted(() => {
      EventsOff("ffmpeg_progress");
      EventsOff("ffmpeg_done");
    });

    const selectInputDir = async () => {
      try {
        SelectDirectory().then((result) => {
          state.inputDirPath = result;
        });
      } catch (err) {
        console.error("选择目录失败:", err);
      }
    };

    const selectInputFile = async () => {
      try {
        SelectFile().then((result) => {
          state.inputFilePath = result;
        });
      } catch (err) {
        console.error("选择文件失败:", err);
      }
    };

    const selectOutputDir = async () => {
      try {
        SelectDirectory().then((result) => {
          state.outputDirPath = result;
        });
      } catch (err) {
        console.error("选择输出目录失败:", err);
      }
    };

    const selectVideoOption = (option) => {
      // 实现选择视频选项的逻辑
      console.log("选择视频选项:", option);
      updateFFmpegCommand(option);
    };

    const selectAudioOption = (option) => {
      // 实现选择音频选项的逻辑
      console.log("选择音频选项:", option);
      updateFFmpegCommand(option);
    };

    const selectImageOption = (option) => {
      // 实现选择图像选项的逻辑
      console.log("选择图像选项:", option);
      updateFFmpegCommand(option);
    };

    const showOptionsHelp = () => {
      // 实现显示选项帮助的逻辑
      console.log("显示选项帮助");
    };

    const updateFFmpegCommand = (option) => {
      // 检查输入路径
      let inputPath = "";
      if (state.inputType === "dir") {
        if (!state.inputDirPath) {
          state.ffmpegCommand = "请先选择输入目录";
          return;
        }
        inputPath = state.inputDirPath;
      } else {
        if (!state.inputFilePath) {
          state.ffmpegCommand = "请先选择输入文件";
          return;
        }
        inputPath = state.inputFilePath;
      }

      // 检查输出目录
      if (!state.outputDirPath) {
        state.ffmpegCommand = "请先选择输出目录";
        return;
      }

      // 根据选择的选项更新FFmpeg命令
      switch (option) {
        case "音视频质量不变":
          state.outputOptions = "-c copy";
          break;
        case "WEB视频流优化":
          state.outputOptions = "-movflags faststart -acodec copy -vcodec copy";
          break;
        case "H264压缩":
          state.outputOptions = "-c:v libx264 -crf 23 -c:a copy";
          break;
        case "H264压缩-intel加速":
          state.outputOptions = "-c:v h264_qsv -preset veryfast -c:a copy";
          break;
        case "H264压缩-AMD加速":
          state.outputOptions = "-c:v h264_amf -preset veryfast -c:a copy";
          break;
        case "H264压缩-NV加速":
          state.outputOptions = "-c:v h264_nvenc -preset veryfast -c:a copy";
          break;
        case "H265压缩":
          state.outputOptions = "-c:v libx265 -crf 23 -c:a copy";
          break;
        case "H265压缩-intel加速":
          state.outputOptions = "-c:v hevc_qsv -preset veryfast -c:a copy";
          break;
        case "H265压缩-AMD加速":
          state.outputOptions = "-c:v hevc_amf -preset veryfast -c:a copy";
          break;
        case "H265压缩-NV加速":
          state.outputOptions = "-c:v hevc_nvenc -preset veryfast -c:a copy";
          break;
        case "转码到mp3":
          state.useOutputExt = true;
          state.outputExt = "mp3";
          state.outputOptions = "-c:a libmp3lame -q:a 2";
          break;
        case "gif(15fps,480p)":
          state.useOutputExt = true;
          state.outputExt = "gif";
          state.outputOptions =
            '-filter_complex "[0:v] scale=480:-1, fps=15, split [a][b];[a] palettegen [p];[b][p] paletteuse"';
          break;
        case "区域模糊":
          state.outputOptions = '-vf "delogo=x=0:y=0:w=100:h=50"';
          break;
        case "视频两倍速":
          state.outputOptions = "-filter:v setpts=0.5*PTS";
          break;
        case "音频两倍速":
          state.outputOptions = '-filter:a "atempo=2.0"';
          break;
        case "视频倒放":
          state.outputOptions = "-vf reverse -af areverse";
          break;
        case "音频倒放":
          state.outputOptions = "-af areverse";
          break;
        case "设置画面比例":
          state.outputOptions = "-aspect 16:9";
          break;
        case "视频0.5倍速 + 光流法补帧到60帧":
          state.outputOptions =
            "-filter:v \"setpts=2.0*PTS,minterpolate='fps=60:mi_mode=mci'\"";
          break;
        case "从视频区间每秒提取n张照片":
          state.outputOptions = "-vf fps=1";
          break;
        case "截取指定数量的帧保存为图片":
          state.outputOptions = "-vframes 1";
          break;
        case "裁切视频画面":
          state.outputOptions = "-vf crop=w:h:x:y";
          break;
        case "视频旋转度数":
          state.outputOptions = '-vf "rotate=90*PI/180"';
          break;
        case "水平翻转画面":
          state.outputOptions = "-vf hflip";
          break;
        case "垂直翻转画面":
          state.outputOptions = "-vf vflip";
          break;
        case "设定至指定分辨率并且自动填充黑边":
          state.outputOptions =
            '-vf "scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2"';
          break;
        case "视频或音乐添加封面图片":
          state.outputOptions =
            "-i cover.jpg -map 0 -map 1 -c copy -disposition:v:1 attached_pic";
          break;
        case "声音响度标准化":
          state.outputOptions = "-filter:a loudnorm";
          break;
        case "音量大小调节":
          state.outputOptions = "-filter:a volume=2.0";
          break;
        case "静音第一个声道":
          state.outputOptions = '-af "pan=stereo|c0=c0|c1=0*c1"';
          break;
        case "静音所有声道":
          state.outputOptions = "-an";
          break;
        case "交换左右声道":
          state.outputOptions = '-af "pan=stereo|c0=c1|c1=c0"';
          break;
      }

      // 更新FFmpeg命令显示
      state.ffmpegCommand = `ffmpeg -i "${inputPath}" ${state.outputOptions} "${state.outputDirPath}/output.mp4"`;
    };

    const runCommand = async () => {
      if (state.isRunning) return;

      state.isRunning = true;
      knownTaskIds.clear(); // 清空已知任务ID集合

      try {
        if (state.inputType === "dir") {
          // 批量处理
          const result = await ConvertBatchFiles(
            state.inputDirPath,
            state.outputDirPath,
            state.useOutputExt,
            state.outputExt,
            state.outputOptions,
            state.fileType
          );
        } else {
          // 单文件处理
          const result = await ConvertSingleFile(
            state.inputFilePath,
            state.outputDirPath,
            state.useOutputExt,
            state.outputExt,
            state.outputOptions
          );
        }
      } catch (err) {
        console.error("转换失败:", err);
        ElMessage.error(`转换失败: ${err}`);
        state.isRunning = false;
      }
    };

    return {
      ...toRefs(state),
      fileConverterTable,
      selectInputDir,
      selectInputFile,
      selectOutputDir,
      selectVideoOption,
      selectAudioOption,
      selectImageOption,
      showOptionsHelp,
      updateFFmpegCommand,
      runCommand,
    };
  },
};
</script>

<style scoped>
.convert-layout {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.convert-main-layout {
  display: flex;
  gap: 10px;
}

.left-panel-layout {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.right-panel-layout {
  flex: 0.5;
  display: flex;
  flex-direction: column;
}

.input-dir-row,
.input-file-row,
.output-dir-row {
  display: flex;
  align-items: center;
  gap: 5px;
}

.output-ext-row {
  display: flex;
  align-items: center;
  gap: 5px;
}

.file-type-combo {
  width: 100%;
}

.options-scrollbar {
  height: 300px;
  overflow-y: auto;
}

.option-item {
  /* padding: 8px; */
  font-size: 13px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.option-item:hover {
  background-color: #f5f7fa;
}

.run-button {
  align-self: flex-end;
  margin-top: 10px;
  width: 100%;
}

:deep(.el-tabs__content) {
  height: 260px;
}

:deep(.el-tabs__header.is-top) {
  /* 自定义样式 */
  margin: 0;
}
</style>
